<template>
  <doc-alert title="【交易】分销返佣" url="https://doc.iocoder.cn/mall/trade-brokerage/"/>

  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="用户编号" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="提现类型" prop="method">
        <el-select
          v-model="queryParams.method"
          placeholder="请选择提现类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.BROKERAGE_WITHDRAW_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="账号" prop="accountNo">
        <el-input
          v-model="queryParams.accountNo"
          placeholder="请输入账号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <!--      <el-form-item label="提现银行" prop="bankName">-->
      <!--        <el-select-->
      <!--          v-model="queryParams.bankName"-->
      <!--          placeholder="请选择提现银行"-->
      <!--          clearable-->
      <!--          class="!w-240px"-->
      <!--        >-->
      <!--          <el-option-->
      <!--            v-for="dict in getStrDictOptions(DICT_TYPE.BROKERAGE_BANK_NAME)"-->
      <!--            :key="dict.value"-->
      <!--            :label="dict.label"-->
      <!--            :value="dict.value"-->
      <!--          />-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="!w-240px">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.BROKERAGE_WITHDRAW_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="申请时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px"/>
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px"/>
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="编号" align="left" prop="id" min-width="120px"/>
      <el-table-column label="用户编号" align="left" prop="userId" min-width="120px"/>
      <el-table-column label="用户昵称" align="left" prop="nickname" min-width="120px"/>
      <!--      <el-table-column label="收款人姓名" align="left" prop="payeeName" min-width="120px"/>-->
      <!--      <el-table-column label="支付宝账号" align="left" prop="alipayAccount" min-width="120px"/>-->
      <!--      <el-table-column label="银行卡号" align="left" prop="bankNo" min-width="120px"/>-->
      <!--      <el-table-column label="开户行名称" align="left" prop="openingBankName" min-width="120px"/>-->
      <el-table-column label="代理商级别" align="left" prop="levelName" min-width="120px"/>
      <el-table-column label="提现方式" align="left" prop="type" min-width="240px">
        <template #default="scope">
          <div>
            <dict-tag :type="DICT_TYPE.BROKERAGE_WITHDRAW_TYPE" :value="scope.row.method"/>
          </div>
          <div
            v-if="getDictLabel(DICT_TYPE.BROKERAGE_WITHDRAW_TYPE, scope.row.method)==='支付宝'">

            <div> 支付宝账户：{{ scope.row.alipayAccount }}</div>
            <div> 收款人姓名：{{ scope.row.payeeName }}</div>

          </div>
          <div v-else>
            <div>开户行名称：{{ scope.row.openingBankName }}</div>
            <div>银行卡号：{{ scope.row.bankNo }}</div>
            <div> 收款人姓名：{{ scope.row.payeeName }}</div>

          </div>
        </template>
      </el-table-column>

      <el-table-column label="提现金额" align="left" prop="amountReceived" min-width="180px">
        <template #default="scope">
          <div>金　额：￥{{ scope.row.amountReceived }}元</div>
          <!--          <div>手续费：￥{{ fenToYuan(scope.row.feePrice) }}</div>-->
        </template>
      </el-table-column>
      <el-table-column label="状态" align="left" prop="status" min-width="120px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.BROKERAGE_WITHDRAW_STATUS" :value="scope.row.status"/>
          <div v-if="scope.row.auditTime" class="text-xs">
            时间：{{ formatDate(scope.row.auditTime) }}
          </div>
          <div v-if="scope.row.auditReason" class="text-xs">
            原因：{{ scope.row.rejectReason }}
          </div>
        </template>
      </el-table-column>

      <!--      <el-table-column label="收款码" align="left" prop="accountQrCodeUrl" min-width="70px">-->
      <!--        <template #default="scope">-->
      <!--          <el-image-->
      <!--            v-if="scope.row.accountQrCodeUrl"-->
      <!--            :src="scope.row.accountQrCodeUrl"-->
      <!--            class="h-40px w-40px"-->
      <!--            :preview-src-list="[scope.row.accountQrCodeUrl]"-->
      <!--            preview-teleported-->
      <!--          />-->
      <!--          <span v-else>无</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column
        label="申请时间"
        align="left"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="备注" align="left" prop="remark"/>
      <el-table-column label="操作" align="left" width="210px" fixed="right">
        <template #default="scope">
          <template v-if="scope.row.status === BrokerageWithdrawStatusEnum.AUDITING.status">
            <el-button
              link
              type="primary"
              @click="handle('approve',scope.row)"
              v-hasPermi="['trade:brokerage-withdraw:audit']"
            >
              通过
            </el-button>
            <el-button
              link
              type="danger"
              @click="openForm(scope.row.id)"
              v-hasPermi="['trade:brokerage-withdraw:audit']"
            >
              驳回
            </el-button>
          </template>
          <template
            v-else-if="scope.row.status === BrokerageWithdrawStatusEnum.AUDITED.status">
            <el-button
              link
              style="color: #2bb673"
              type="primary"
              @click="handle('viewImg',scope.row)"
              v-hasPermi="['trade:brokerage-withdraw:audit']"
            >
              查看转账记录
            </el-button>
          </template>
          <template
            v-else-if="scope.row.status === BrokerageWithdrawStatusEnum.REJECTED.status">
            <el-popover
              placement="bottom"
              title="原因："
              :width="250"

              trigger="click"
              :content="scope.row.rejectReason"
            >
              <template #reference>
                <el-button style="color: #e6a23c" link type="primary">查看驳回原因</el-button>
              </template>
            </el-popover>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <BrokerageWithdrawRejectForm ref="formRef" @success="getList"/>

  <Dialog v-model="uploadTransferImg" title="上传凭证" width="600">
    <div v-if="formData.option===1">
      <el-form-item label="转账成功凭证" prop="transferPic">
        <UploadImg v-model="formData.transferPic" height="80px"/>
      </el-form-item>
      <el-form
        ref="formRef"
        label-position="top"
        :model="formData"
        :rules="formRules"
        label-width="100px"

      >
        <el-form-item label="备注" prop="auditReason">
          <el-input style="display: flex;" v-model="formData.remark" :rows="5"
                    type="textarea"
                    placeholder="(选填)"/>
        </el-form-item>
      </el-form>
      <el-button
        size="small"
        type="primary"
        @click="confirmApprove"
      >
        确定上传
      </el-button>
    </div>
    <div v-else>
      <div style="text-align: center">
        <el-image
          style="width: 400px; "
          :src="formData.transferPic"
          :zoom-rate="1.2"
          :max-scale="7"
          :min-scale="0.2"
          :preview-src-list="[formData.transferPic]"
          :initial-index="4"
          fit="cover"
        />
      </div>
    </div>
  </Dialog>

</template>

<script setup lang="ts">
import {DICT_TYPE, getDictLabel, getIntDictOptions, getStrDictOptions} from '@/utils/dict'
import {dateFormatter, formatDate} from '@/utils/formatTime'
import * as BrokerageWithdrawApi from '@/api/mall/trade/brokerage/withdraw'
import * as DistributionApi from "@/api/member/distribution";
import BrokerageWithdrawRejectForm from './BrokerageWithdrawRejectForm.vue'
import {BrokerageWithdrawStatusEnum, BrokerageWithdrawTypeEnum} from '@/utils/constants'
import type {Spu} from "@/api/mall/product/spu";

defineOptions({name: 'BrokerageWithdraw'})

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  userId: null,
  method: '',
  name: null,
  accountNo: null,
  bankName: null,
  status: '',
  auditReason: null,
  createTime: [],
  remark: null,
})
const queryFormRef = ref() // 搜索的表单
/** 上传转账截图弹窗开启或关闭 */
const uploadTransferImg = ref(false)
const formData = reactive({
  transferPic: '', // 审核通过转账图
  remark: '',
  type: 'APPROVE',
  option: 1
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await DistributionApi.brokerageRecordPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false

  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (id: number) => {
  formRef.value.open(id)
}

/** 审核通过 */
const handleApprove = async (id: number) => {
  try {
    loading.value = true
    await message.confirm('确定要审核通过吗？')
    await BrokerageWithdrawApi.approveBrokerageWithdraw(id)
    await message.success(t('common.success'))
    await getList()
  } finally {
    loading.value = false
  }
}

/** 重置按钮操作 */
const handle = (type, item) => {
  formData.id = item.id
  switch (type) {
    case 'approve':
      formData.option = 1
      uploadTransferImg.value = true
      break
    case 'viewImg':
      formData.transferPic = item.transferPic
      formData.option = 2
      uploadTransferImg.value = true
      break
  }
}
const confirmApprove = async () => {
  await DistributionApi.withdrawalRecordUpdate(formData)
  uploadTransferImg.value = false
  message.success('操作成功')
  getList()
}
/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
